package com.sync.qustion;


/**
 * 方法抛出异常后，会释放锁？
 *  展示不抛出异常钱和抛出异常后的对比：
 *      一旦抛出了异常，第二个线程会立即进入同步方法，意味着锁已经释放
 * */
public class SimpleMethodNoStatic5 implements Runnable {

    static SimpleMethodNoStatic5 simpleMethodNoStatic = new SimpleMethodNoStatic5();

    static int count = 0;
    public static void main(String[] args) {
        Thread t1 = new Thread(simpleMethodNoStatic);
        Thread t2 = new Thread(simpleMethodNoStatic);
        t1.start();
        t2.start();
        while(t1.isAlive() || t2.isAlive());
        System.out.println(" finish " +count);

    }

    @Override
    public void run() {
        method();
        cast();
    }

    // synchronized 修饰方法的时候默认里面对象是this对象
    public synchronized void method() throws IllegalArgumentException{
        System.out.println("synchronized" +Thread.currentThread().getName()+"静态加锁的方法");
        for (int i = 0; i < 100000; i++) {
            count++;
        }
        try {
            throw new IllegalArgumentException("xxxxxxxxx");
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
        System.out.println("synchronized " +Thread.currentThread().getName()+"运行结束");
    }
    // synchronized 修饰方法的时候默认里面对象是this对象
    public synchronized void cast(){
        System.out.println(Thread.currentThread().getName()+"非静态加锁的方法哦");
        for (int i = 0; i < 100000; i++) {
            count--;
        }
        System.out.println(Thread.currentThread().getName()+"运行结束");

    }
}
